/**
 * @file 2-bitfield.c
 * @author your name (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2025-03-24
 * 
 * 位域不可以跨字节！
 * 
 * @copyright Copyright (c) 2025
 * 
 */

#include <stdio.h>
#include <stdint.h>
#include <memory.h>

#pragma pack(push, 1)

typedef struct{
    uint16_t ch1 : 11;
    uint16_t ch2 : 11;
    uint16_t ch3 : 11;
    uint16_t ch4 : 11;
} data_t;

typedef union rc_channels{
struct{
    uint16_t ch1 : 11;
    uint16_t ch2 : 11;
    uint16_t ch3 : 11;
    uint16_t ch4 : 11;
    uint16_t ch5 : 11;
    uint16_t ch6 : 11;
    uint16_t ch7 : 11;
    uint16_t ch8 : 11;
    uint16_t ch9 : 11;
    uint16_t ch10 : 11;
    uint16_t ch11 : 11;
    uint16_t ch12 : 11;
    uint16_t ch13 : 11;
    uint16_t ch14 : 11;
    uint16_t ch15 : 11;
    uint16_t ch16 : 11;
}channels;
uint8_t buf[22];
} rc_channels_t;

#pragma pack(pop)

// 
void test01(){
    data_t data={};
    data.ch1 = 1574;
    data.ch2 = 1500;
    data.ch3 = 2047;
    data.ch4 = 1500;

    printf("struct size=%lu\n", sizeof(data));

    uint8_t       buf[22] = {0x27, 0xE6, 0x2E, 0x77, 0x01};
    // memcpy(rc.buf, );
    rc_channels_t rc={.buf={0x27, 0xE6, 0x2E, 0x77, 0xB9, 0x8B, 0x70, 0xEE, 0x72}};

    rc_channels_t rc2;
    rc2.channels.ch1 = 0x7FF;
    rc2.channels.ch2 = 0x7FF;
    rc2.channels.ch3 = 0x7FF;
    rc2.channels.ch4 = 0x7FF;
}

//
void sbus_pack(){
    uint16_t      channels[16] = {1500, 1600, 1700, 1800, 1900, 2000};
    rc_channels_t rc1 = {};
    rc_channels_t rc2 = {.buf = {0x27, 0xE6, 0x2E, 0x77, 0xB9, 0x8B, 0x70, 0xEE, 0x72}};

    // 通道数据打包（每个通道11bit）
    int byte_idx = 0, bit_idx = 0;
    for(int i = 0; i < 16; i++) {
        uint16_t val = channels[i];
        
        // 处理超出范围的数值
        if(val > 2047) val = 2047;

        // 按位填充数据
        for(int b = 0; b < 11; b++) {
            if(val & (1 << b)) { // LSB first
                rc1.buf[byte_idx] |= (1 << bit_idx);
            }
            
            if(++bit_idx >= 8) {
                bit_idx = 0;
                byte_idx++;
            }
        }
    }
    printf("\n");
}

int main(int argc, char *argv[]) {
    sbus_pack();

    return 0;
}

